package com.kaduoxee.ebooks.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kaduoxee.ebooks.entity.User;
import com.kaduoxee.ebooks.service.impl.UserServiceImpl;
import com.kaduoxee.ebooks.util.ImgVerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
public class UserController {
    private final String register_page = "/register";
    private final String login_page = "/login";
    private final String index_page = "/index";

    @Autowired
    private UserServiceImpl userService;

    @GetMapping("/register")
    public String register(){
        return register_page;
    }

    @GetMapping("/login")
    public String login(){
        return login_page;
    }

    @RequestMapping("/getVerificationCode")
    public void getVerificationCode(HttpServletRequest request,
                                    HttpServletResponse response, HttpSession session)
            throws IOException {
        request.setCharacterEncoding("utf-8");
        ImgVerifyCodeUtils codeUtils = new ImgVerifyCodeUtils();
        BufferedImage image = codeUtils.getImage();
        //将验证码存入session
        session.setAttribute("text",codeUtils.getText());
        System.out.println(session.getAttribute("text")+"=========================");
        //将图片响应给浏览器
        ImgVerifyCodeUtils.output(image,response.getOutputStream());
    }

    @PostMapping(value = "/checkVerify", headers = "Accept=application/json")
    @ResponseBody
    public boolean checkVerify(@RequestParam String verifyInput, HttpSession session) {
        try {
            //从session中获取正确验证码
            String random = (String) session.getAttribute("text");
            return random != null && !"".equals(random) && random.equalsIgnoreCase(verifyInput);
        } catch (Exception e) {
            return false;
        }
    }

    @ResponseBody
    @GetMapping("getText")
    public String getText(HttpSession session){
        return (String) session.getAttribute("text");
    }

    @ResponseBody
    @PostMapping("existUser")
    public boolean existUser(String username,Model model){
        System.out.println(username+"============un");
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        User user = userService.getOne(queryWrapper);
        System.out.println(user+"====================");
        model.addAttribute("iptClass", "input-placeholder");
        return user == null;
    }

    @PostMapping("/user")
    public String saveUser(User user){
        userService.save(user);
        return login_page;
    }

    @PostMapping("/loginVerify")
    public String loginVerify(User user, HttpSession session, Model model) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",user.getUsername());
        //提前确保用户名存在才能提交登录表单
        User res = userService.getOne(queryWrapper);
        model.addAttribute("iptClass", "input-placeholder");
        if (res.getPassword().equals(user.getPassword())){
            session.setAttribute("user",res);
            return "redirect:" + index_page;
        }else {
            model.addAttribute("username", user.getUsername());
            model.addAttribute("msg", "密码错误");
            return login_page;
        }

    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:"+index_page;
    }

}
